package com.ncu.xrpc.util;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: xiongwb
 * Date: 2021/9/9 19:49
 * Describe: Hessian序列化工具
 */
public class HessianUtil {

    /**
     * Hessian序列化
     * @param object
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Hessian2Output h2s = new Hessian2Output(baos);
        h2s.writeObject(object);
        h2s.flush();
        byte[] bytes = baos.toByteArray();
        baos.close();
        h2s.close();
        return bytes;
    }

    /**
     * 反序列化
     * @param bytes
     * @return
     * @throws IOException
     */
    public static Object deserialize(byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        Hessian2Input h2i = new Hessian2Input(bais);

        Object object = h2i.readObject();

        bais.close();
        h2i.close();
        return object;
    }

}
